package net.zhengxinyun.performance.App.appCtrl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.App.dto.DepartIndexDataDTO;
import net.zhengxinyun.performance.App.dto.DuChaDTO.DCTaskDTO;
import net.zhengxinyun.performance.App.dto.DuChaDTO.ZDProcjectDTO;
import net.zhengxinyun.performance.App.dto.IncentiveDTO;
import net.zhengxinyun.performance.App.dto.IndexUserDTO;
import net.zhengxinyun.performance.App.dto.report.LeadScoreDTO;
import net.zhengxinyun.performance.App.dto.report.ReportDTO;
import net.zhengxinyun.performance.App.dto.ScoreDTO;
import net.zhengxinyun.performance.App.dto.report.ReportDataDTO;
import net.zhengxinyun.performance.App.entity.*;
import net.zhengxinyun.performance.App.service.DuCha.DuchaService;
import net.zhengxinyun.performance.App.service.EvalScoreMag.EvalScoreMagService;
import net.zhengxinyun.performance.App.service.cityIndex.CityIndexService;
import net.zhengxinyun.performance.App.service.deptIndex.DeptIndexService;
import net.zhengxinyun.performance.App.service.townIndex.TownIndexService;
import net.zhengxinyun.performance.App.service.unifyService.UnifyService;
import net.zhengxinyun.performance.Util.*;
import net.zhengxinyun.performance.Util.httpsUitl.HttpClientService;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.data.UserAppDTO;
import net.zhengxinyun.performance.dto.AppDTO.ListViewDTO;
import net.zhengxinyun.performance.dto.HeadColums;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.*;
import net.zhengxinyun.performance.service.criteria.CriteriaService;
import net.zhengxinyun.performance.service.departClass.DepartClassService;
import net.zhengxinyun.performance.service.departClass.DepartHeadService;
import net.zhengxinyun.performance.service.department.DepartmentService;
import net.zhengxinyun.performance.service.incentive.IncentiveService;
import net.zhengxinyun.performance.service.incentive.IncentiveTypeSerice;
import net.zhengxinyun.performance.service.indicators.CountryIndicatorsService;
import net.zhengxinyun.performance.service.indicators.TownScoreService;
import net.zhengxinyun.performance.service.leaders.LeaderService;
import net.zhengxinyun.performance.service.login.UserService;
import net.zhengxinyun.performance.service.setTime.SetTimeService;
import net.zhengxinyun.performance.service.workSupervision.WorkScoreService;
import net.zhengxinyun.performance.service.yearSummaryScore.YearSummaryScoreService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 综合App的 登录调取的api 接口
 */

@RestController
@RequestMapping("/app")
public class UnifyAppCtrl extends BaseCtrl {

    @Autowired
    private UserService userService;  // 用户管理service
    @Autowired
    private SetTimeService setTimeService; // 自定义设置 Service
    @Autowired
    private DepartHeadService headService; // 单位分类表头 service
    @Autowired
    private YearSummaryScoreService yearSummaryScoreService; //年度绩效考核 service

    @Autowired
    private CountryIndicatorsService cityIndexService; // 市对县指标Web service
    @Autowired
    private TownScoreService TownScoreService;// 县对乡考核分数 service
    @Autowired
    private IncentiveService incentiveService;// 正向激励web service

    @Autowired
    private WorkScoreService workScoreService;// 工作督查service

    @Autowired
    private CityIndexService AppcityIndexService; // App市对县指标service

    @Autowired
    private TownIndexService appTwonService;

    @Autowired
    private UnifyService unifyService;
    @Autowired
    private DeptIndexService deptIndexService;
    @Autowired
    private DepartClassService deptclass;


    @Autowired
    private LeaderService leaderService;

    @Autowired
    private DuchaService duchaService;

    @Autowired
    private DepartmentService departmentService;

    private String address = SystemApiUtl.SERVICEADDRESS + ":" + SystemApiUtl.ZDTESTHOST;


    @Autowired
    private EvalScoreMagService evalScoreMagService;

    @Autowired
    private IncentiveTypeSerice incentiveTypeSerice;

    @Autowired
    private CriteriaService criteriaService;

    // 登录接口 调用获取用户基本数据
    @GetMapping("/getUserInfo")
    public Result<HashMap<String, Object>> getUserInfo(HttpServletRequest request) {

        String tel = request.getParameter("tel");
        if (StringUtils.isBlank(tel)) {
            return ResultUtils.getResults(Result.Status.ERROR, "暂无用户", null);
        }

        UserFilter userFilter = new UserFilter();
        userFilter.setUserPhone(tel);
        List<UserFilter> userFilters = userService.queryUsers(userFilter);

        HashMap<String, Object> map = new HashMap<>();
        map.put("listuser", userFilters);
        System.out.println("-------接口： /getUserInfo");
        return ResultUtils.getResults(Result.Status.SUCCESS, "获取成功", map);


    }


    //登录首页数据 县领导
    @PostMapping("/homeData")
    public Result<HashMap<String, Object>> insert(@RequestBody UserAppDTO param) {
        HashMap<String, Object> dataMap = new HashMap<>();
        SetTimeEntity currentYear = setTimeService.findByIndexClass("3");
        String currentYears = currentYear.getStartTime();

     /*   HashMap<String, Object> map = appHomeService.CitySocure(currentYear.getStartTime());

        String datatime =param.getDatetime();
        if(StringUtils.isBlank(param.getDatetime())){
            datatime = DateUtils.getLastMonth();
        }
        if(StringUtils.isBlank(param.getDepartCode()))
        {
            return ResultUtils.getResults(Result.Status.ERROR, "单位code为空",null);
        }
        List<DepartClassHead> heads = headService.queryByDatetime(currentYear.getStartTime());
        HashMap<String, Object> departScore = yearSummaryScoreService.getDepartScore(heads, datatime,param.getDepartCode(),null);


        dataMap.put("firstRow",map);
        dataMap.put("secondRow",departScore);*/


        // 市对县指标
        CountryIndicatorsFilter filter = new CountryIndicatorsFilter();
        if (StringUtils.isBlank(filter.getDateTime())) {
            filter.setDateTime(currentYear.getStartTime());
            filter.setMonthTime(DateUtils.getLastMonth(currentYears));
            filter.setAudit(1 + "");
        }
        List<CountryIndicatorsFilter> indexScore = AppcityIndexService.getIndexScore(filter, null);
        double finalScoreSum = indexScore.stream().mapToDouble(CountryIndicatorsFilter::getFinalScore).sum();
        int weight = indexScore.stream().mapToInt(CountryIndicatorsFilter::getWeight).sum();
        //计算得分  得分 = 权重x得分率/100
        double rate = 0;
        if (0 != weight) {

            rate = (finalScoreSum / weight) * 100;
            rate = Util.keepNumberFormat(2, rate);
        }


        //  正向激励
        IncentiveFilter dtofilter = new IncentiveFilter();
        dtofilter.setAudit("1");
        dtofilter.setDateTime(currentYears);
        List<IncentiveFilter> listincet = incentiveService.queryAll(dtofilter);
        double sumIncent = listincet.stream().mapToDouble(IncentiveFilter::getDoublePoint).sum();
        sumIncent = Util.keepNumberFormat(2, sumIncent);

        // 专项工作督查
        WorkScoreFilter workFilter = new WorkScoreFilter();
        workFilter.setYear(currentYears);
        List<WorkScoreFilter> query = workScoreService.query(workFilter);
        double sumWroks = query.stream().mapToDouble(WorkScoreFilter::getDouleFinalScore).sum();
        sumWroks = Util.keepNumberFormat(2, sumWroks);

        double totolScore = (finalScoreSum*0.6)+(sumIncent>=3?3:sumIncent)-sumWroks;
        dataMap.put("rank", "-");
        dataMap.put("currentScore", DataUtil.formatNumberDouble(2,totolScore));
        dataMap.put("indexScore", rate); //指标得分率
        dataMap.put("SpecialWorkScore", -sumWroks); // 专项工作督查
        dataMap.put("insprireScore", sumIncent); // 正想激励
        dataMap.put("VisitCheckScore", "-"); // 察访核验
        dataMap.put("publicTest", "-");// 公众评议
        List<DepartClassFilter> classes = deptclass.query(new DepartClassFilter());
        classes.sort(Comparator.comparing(DepartClassFilter::getId));
        dataMap.put("otherRoles", classes);
        System.out.println("-------接口： /homeData");
        return ResultUtils.getResults(Result.Status.SUCCESS, "首页登录数据返回成功", dataMap);
    }

    //各乡镇得分排名 (年度绩效 )
    @PostMapping("/deptRanks")
    public Result<HashMap<String, Object>> query(@RequestBody DepartmentFilter param) {
        SetTimeEntity currentYear = setTimeService.findByIndexClass("3");
        String datatime = param.getDatetime();
        if (StringUtils.isBlank(param.getDatetime())) {
            datatime = DateUtils.getLastMonth(datatime);
        }

        List<DepartClassHead> heads = headService.queryByDatetime(currentYear.getStartTime());
        HashMap<String, Object> departScore = yearSummaryScoreService.getDepartScore(heads, datatime, null, param.getDepartType(), null);
        List<Map<String, Object>> dataList = (List<Map<String, Object>>) departScore.get("tableData");

        List<HeadColums> tableHead = (List<HeadColums>) departScore.get("tableHead");
        Map<String, String> collect = tableHead.stream().collect(Collectors.toMap(o -> o.getKey(), o -> o.getTitle()));

        List<ScoreDTO> rankList = new ArrayList<>();
        for (Map<String, Object> objectMap : dataList) {
            String fialScore = objectMap.get("totalScore") + "";
            Object departCode = objectMap.get("departCode");
            rankList.add(new ScoreDTO(DataUtil.doubleParse(fialScore), departCode + ""));


            List<ListViewDTO> lvdtos = new ArrayList<>();
            for (Map.Entry<String, Object> entry : objectMap.entrySet()) {
                String key = entry.getKey() + "";
                //rankList.add( new ScoreDTO( )  )

                if ("departName,datetime,totalScore,departCode,departType".contains(key)) {
                    continue;
                }


                lvdtos.add(new ListViewDTO(collect.get(entry.getKey() + "") + "",
                        entry.getValue() + "", objectMap.get("departCode") + ""));

            }
            objectMap.put("listView", lvdtos);
        }
        // 高到底排序
        rankList.sort(Comparator.comparing(ScoreDTO::getFinalScore).reversed());
        //rankList =rankList.stream().sorted(Comparator.comparing(ScoreDTO::getFinalScore)).collect(Collectors.toList());

        //设置排名
        for (int i = 0; i < rankList.size(); i++) {
            if (rankList.get(i).getFinalScore() != 0) {
                rankList.get(i).setRank(i + 1);
            }
        }
        //  list 转map
        Map<String, Integer> rankMap = rankList.stream().collect(Collectors.toMap(o -> o.getDepartCode(), o -> o.getRank()));
        for (Map<String, Object> objectMap : dataList) {
            String departcode = objectMap.get("departCode") + "";

            Integer integer = rankMap.get(departcode);
            if (integer.intValue() != 0)
                objectMap.put("rank", integer.intValue() + "");
            else
                objectMap.put("rank", "-");
        }


        System.out.println("-------接口： /deptRanks");
        return ResultUtils.getSuccessResults(departScore);


    }

    //指标得分列表； 乡镇或者单位指标分数
    @PostMapping("/indexDetails")
    public Result<HashMap<String, Object>> indexDetails(@RequestBody IndexUserDTO dto) {
        HashMap<String, Object> map = new HashMap<>();
        String currentYear = getCurrentYear();
        List<ScoreDTO> scoreDTOS = new ArrayList<>();
        String departType = "";

        UserFilter userInfo = getUserInfo(dto.getUserPhone());
       /* if(StringUtils.isBlank(dto.getDepartcode()))
        {
            dto.setDepartcode(userInfo.getDepartcode());
        }*/

        if (StringUtils.isBlank(dto.getScoreType())) {
            return ResultUtils.getResults(Result.Status.ERROR, "/indexDetails接口的scoreType参数分别为：指标得分，正向激励，专项工作督查", null);
        }

        if ("指标得分".equals(dto.getScoreType().trim())) {
            dto.setScoreType("绩效指标");
        }
        switch (dto.getScoreType()) {
            //指标得分

            case "绩效指标":
                if (StringUtils.isBlank(dto.getDepartcode()) && StringUtils.isNotBlank(dto.getDepartType())) {
                    //return  ResultUtils.getResults(Result.Status.ERROR,"单位Code为空！！！",null);
                    departType = dto.getDepartType();
                } else {
                    DepartmentEntity depart = getDepartByCode(dto.getDepartcode());
                    departType = depart.getDepartType();
                }


                //点击乡镇， 某个乡镇下所有指标得分
                if ("乡镇".equals(departType)) {

                    if(StringUtils.isBlank(dto.getDepartcode()))
                    {
                        dto.setDepartcode(userInfo.getDepartcode());
                    }

                    TownIndicatorsFilter townFilter = new TownIndicatorsFilter();
                    if (StringUtils.isBlank(dto.getDepartcode())) {
                        return null;
                    }
                    townFilter.setDepartCode(dto.getDepartcode());
                    townFilter.setDateTime(DateUtils.getLastMonth(currentYear));
                    townFilter.setIndexYear(currentYear);

                    List<TownIndicatorsFilter> indictScore = TownScoreService.getIndictScore(townFilter);

                    for (TownIndicatorsFilter item : indictScore) {

                        double finalScore = StringUtils.isBlank(item.getFinalScore()) ? 0 : Double.parseDouble(item.getFinalScore());
                        double score = StringUtils.isBlank(item.getScore()) ? 0 : Double.parseDouble(item.getScore());
                        int weight = StringUtils.isBlank(item.getWeight()) ? 0 : Integer.parseInt(item.getWeight());
                        int rank = item.getRankInt();
                        scoreDTOS.add(new ScoreDTO(Long.parseLong(item.getIndexId()), finalScore, score, weight, rank, null, dto.getDepartcode(), item.getDateTime(), null, item.getIndexName()));
                    }
                    map.put("data", scoreDTOS);
                    map.put("datetime",townFilter.getDateTime());
                    System.out.println("-------接口： /indexDetails");
                    return ResultUtils.getSuccessResults(map);
                } else if ("县直单位".equals(departType)||"管理员".equals(departType)) {
                    CountryIndicatorsFilter indexFilter = new CountryIndicatorsFilter();
                    indexFilter.setIndexType("二级指标");

                    if(StringUtils.isNotBlank(dto.getDepartcode()))
                    {
                        indexFilter.setLeadUnit(dto.getDepartcode());
                    }

                  /*  if("admin".equals(userInfo.getUserPermissions())){
                        indexFilter.setLeadUnit(null);
                    }*/

                    // 设置日期， 这个日期有点奇葩啊；干
                    if (StringUtils.isBlank(dto.getDateTime())) {
                        indexFilter.setMonthTime(DateUtils.getLastMonth(currentYear));
                        indexFilter.setDateTime(currentYear);
                    }else {
                        indexFilter.setMonthTime(dto.getDateTime());
                        indexFilter.setDateTime(dto.getDateTime().substring(0,4));
                    }


                    UserEntity userEntity = new UserEntity();
                    BeanUtils.copyProperties(userInfo, userEntity);
                    List<CountryIndicatorsFilter> listIndesScore = cityIndexService.querySecondIndex(indexFilter, userEntity);
                    for (CountryIndicatorsFilter item : listIndesScore) {
                        ScoreDTO score = new ScoreDTO(item.getId(), item.getFinalScore() == null ? 0 : item.getFinalScore(), item.getScore() == null ? 0 : item.getScore(), item.getWeight(), item.getRank(), null, item.getDepartcode(), item.getDateTime(), item.getDepartment(), item.getIndexName());
                        scoreDTOS.add(score);
                    }

                    map.put("data", scoreDTOS);

                    List<ScoreDTO> scoreDTOS1 = filterCityIndexs(listIndesScore, userInfo.getId()+"");
                    map.put("owners", scoreDTOS1);
                    map.put("datetime", DateUtils.getLastMonth(currentYear));
                    System.out.println("-------接口： /indexDetails");
                    return ResultUtils.getSuccessResults(map);

                }
            case "正向激励":
                IncentiveFilter dtofilter = new IncentiveFilter();
                dtofilter.setAudit("1");
                dtofilter.setDateTime(currentYear);
                if(!"admin".equals(userInfo.getUserPermissions())){  //过滤超级管理员
                    dtofilter.setDepartCode(dto.getDepartcode());
                }

                IncentiveTypeEntity infiter = new IncentiveTypeEntity();
                List<IncentiveTypeFilter> listtypes = incentiveTypeSerice.queryType(infiter);


                List<IncentiveDTO> incentiveDTOS = incentiveService.typeScore(currentYear, dtofilter.getDepartCode());// 不过滤

                Map<Long, Double> collect = incentiveDTOS.stream().collect(Collectors.toMap(o -> o.getTypeId(), o -> o.getSum()));

                double sumtype = 0;
                for (IncentiveTypeFilter listtype : listtypes) {
                    Double aDouble = collect.get(listtype.getId());
                    if (ObjectUtils.isBlank(aDouble)) {
                        scoreDTOS.add(new ScoreDTO(0, listtype.getTypeName(), listtype.getId(), currentYear));
                    } else {
                        scoreDTOS.add(new ScoreDTO( DataUtil.formatNumberDouble(3,aDouble.doubleValue())  , listtype.getTypeName(), listtype.getId(), currentYear));
                        sumtype = sumtype + aDouble.doubleValue();
                    }

                }

                List<IncentiveDTO> filterintenct = incentiveService.typeScore(currentYear, dto.getDepartcode());// 过滤

                List<ScoreDTO> scoreDTOS1 = filetIncentive(listtypes, filterintenct, currentYear);


                map.put("data", scoreDTOS);
                map.put("owners", scoreDTOS1);
                map.put("totalScore", DataUtil.formatNumberDouble(3,sumtype));
                map.put("rank", "-");
                map.put("datetime", currentYear);
                System.out.println("-------接口： /indexDetails");
                return ResultUtils.getSuccessResults(map);
            case "专项工作督查":
                WorkScoreFilter filter = new WorkScoreFilter();
                filter.setYear(currentYear);
                if(!"admin".equals(userInfo.getUserPermissions())){  //过滤超级管理员
                    filter.setDepartCode(dto.getDepartcode());
                }
                List<WorkScoreFilter> query = workScoreService.query(filter);
                for (WorkScoreFilter item : query) {
                    double fianlscore = item.getFinalScore() == null ? 0 : -item.getFinalScore();
                    scoreDTOS.add(new ScoreDTO(item.getId(), fianlscore, 0, 0, 0, null, null, null, null, item.getIndexName()));


                }
               /* filter.setDepartCode(dto.getDepartcode());
                query = workScoreService.query(filter);*/
                List<WorkScoreFilter> filterworks = filterWorkIndex(query, userInfo.getId()+"");
                List<ScoreDTO> owner = new ArrayList<>();
                for (WorkScoreFilter item : filterworks) {
                    double fianlscore = item.getFinalScore() == null ? 0 : -item.getFinalScore();
                    owner.add(new ScoreDTO(item.getId(), fianlscore, 0, 0, 0, null, null, null, null, item.getIndexName()));


                }

                map.put("data", scoreDTOS);
                map.put("owners", owner);
                map.put("datetime",currentYear);
                System.out.println("-------接口： /indexDetails");
                return ResultUtils.getSuccessResults(map);

        }
        System.out.println("-------接口： /indexDetails");
        return null;
    }


    //指标三级页面 指标图表 历月数据
    @PostMapping("/analysis")
    public Result<HashMap<String, Object>> analysisIndex(@RequestBody IndexUserDTO dto) {
        HashMap datamap = new HashMap();
        String currentYear = getCurrentYear();

        if (StringUtils.isBlank(dto.getScoreType())) {
            if (StringUtils.isBlank(dto.getDepartcode()) || ObjectUtils.isBlank(dto.getIndexId())) {
                return ResultUtils.getResults(Result.Status.ERROR, "单位Code为空！！！或者indexId为空", null);
            }
            DepartmentEntity depart = getDepartByCode(dto.getDepartcode());
            if (depart.getDepartType().equals("乡镇")) {
                dto.setScoreType("townIndex");
            } else if (depart.getDepartType().equals("县直单位")) {
                dto.setScoreType("cityIndex");
            }
        }

        switch (dto.getScoreType()) {
            case "townIndex":
                List<ScoreDTO> scoreDTOS = appTwonService.queryYearIndexInfo(dto.getIndexId() + "", dto.getDepartcode(), currentYear);
                datamap.put("data", scoreDTOS);
                break;
            case "cityIndex":
                List<ScoreDTO> yearCityIndex = AppcityIndexService.getYearCityIndex(dto.getIndexId(), currentYear);
                datamap.put("data", yearCityIndex);
                break;
            case "deptIndex":
                List<DepartIndexDataDTO> departIndexDataDTOS = deptIndexService.IndexWholeScore(dto.getIndexId(), dto.getDepartcode());
                datamap.put("data", departIndexDataDTOS);
                break;


        }
        /*if ("乡镇".equals(dto.getDepartType().trim())) {
            List<ScoreDTO> scoreDTOS = appTwonService.queryYearIndexInfo(dto.getIndexId() + "", dto.getDepartcode(), currentYear);
            datamap.put("data",scoreDTOS);
        }else if("县直单位".equals(dto.getDepartType().trim())){
            List<ScoreDTO> yearCityIndex = AppcityIndexService.getYearCityIndex(dto.getIndexId(),currentYear);
            datamap.put("data",yearCityIndex);
        }else if("专项工作督查".equals(dto.getDepartType()))
        {

        }else if("县直单位指标".equals(dto.getDepartType().trim()))
        {
            List<DepartIndexDataDTO> departIndexDataDTOS = deptIndexService.IndexWholeScore(dto.getIndexId(), dto.getDepartcode());
            datamap.put("data",departIndexDataDTOS);
        }*/
        System.out.println("-------接口： //analysis");
        return ResultUtils.getSuccessResults(datamap);
    }


    //市对县报送情况1，乡镇报送情况2， 县直单位报送情况3，报送情况
    @PostMapping("/report/info")
    public Result<HashMap<String, Object>> reportInfo(@RequestBody ReportDTO dto) {
        int indexClass = dto.getIndexClass();
        //String userPhone = dto.getUserPhone();
        if(0==indexClass)
        {
            return  ResultUtils.getResults(Result.Status.ERROR,"indexClass不能为空",null);
        }
        HashMap datamap = new HashMap();
        String currentYear = getCurrentYear();
        dto.setDatetime(currentYear);
        List<ReportDTO> reportData = unifyService.getReportData(dto);

        datamap.put("data", reportData);
        datamap.put("datetime",DateUtils.getLastMonth(currentYear));
        datamap.put("curentYear",getCurrentYear());
        System.out.println("-------接口： /report/info");
        return ResultUtils.getSuccessResults(datamap);
    }

    //报送情况二级页面
    @PostMapping("/report/second")
    public Result<HashMap<String, Object>> reportSecond(@RequestBody ReportDTO dto) {
        HashMap datamap = new HashMap();
        if (dto.getIndexClass() == 0 || ObjectUtils.isBlank(dto.getIndexId())) {
            return ResultUtils.getResults(Result.Status.ERROR, "指标id或类型为空，啊钢你少传参数了", null);
        }
        List<ReportDataDTO> reportDataDTOS = unifyService.singleIndexReport(dto.getIndexId(), dto.getIndexClass());
        datamap.put("data", reportDataDTOS);
        System.out.println("-------接口： /report/second");
        return ResultUtils.getSuccessResults(datamap);
    }

    // 绩效登录页面
    @PostMapping("/login/home")
    public Result<HashMap<String, Object>> loginHome(@RequestBody UserAppDTO param) {
        HashMap dataMap = new HashMap();
        String currentYear = getCurrentYear();

        String appRole = param.getAppRole();
        switch (appRole) {
            case "县领导":
                //永泰县预计得分 排名
                dataMap.put("rank", "-");//预计排名
                dataMap.put("currentScore", "-");//预计排名
                List<DepartClassFilter> query = deptclass.query(new DepartClassFilter());
                dataMap.put("otherRoles", query);
                // 市对县指标
                CountryIndicatorsFilter filter = new CountryIndicatorsFilter();
                if (StringUtils.isBlank(filter.getDateTime())) {
                    filter.setDateTime(currentYear);
                    filter.setMonthTime(DateUtils.getLastMonth(currentYear));
                    filter.setAudit(1 + "");
                }
                List<CountryIndicatorsFilter> indexScore = AppcityIndexService.getIndexScore(filter, null);
                double finalScoreSum = indexScore.stream().mapToDouble(CountryIndicatorsFilter::getFinalScore).sum();
                int weight = indexScore.stream().mapToInt(CountryIndicatorsFilter::getWeight).sum();
                //计算得分  得分 = 权重x得分率/100
                double rate = 0;
                if (0 != weight) {

                    rate = (finalScoreSum / weight) * 100;
                    rate = Util.keepNumberFormat(2, rate);
                }


                //  正向激励
                IncentiveFilter dtofilter = new IncentiveFilter();
                dtofilter.setAudit("1");
                dtofilter.setDateTime(currentYear);
                List<IncentiveFilter> listincet = incentiveService.queryAll(dtofilter);
                double sumIncent = listincet.stream().mapToDouble(IncentiveFilter::getDoublePoint).sum();
                sumIncent = Util.keepNumberFormat(2, sumIncent);

                // 专项工作督查
                WorkScoreFilter workFilter = new WorkScoreFilter();
                workFilter.setYear(currentYear);
                List<WorkScoreFilter> zhuanxiang = workScoreService.query(workFilter);
                double sumWroks = zhuanxiang.stream().mapToDouble(WorkScoreFilter::getDouleFinalScore).sum();
                sumWroks = Util.keepNumberFormat(2, sumWroks);


                dataMap.put("indexScore", rate); //指标得分率
                dataMap.put("SpecialWorkScore", -sumWroks); // 专项工作督查
                dataMap.put("insprireScore", sumIncent); // 正想激励
                dataMap.put("VisitCheckScore", "-"); // 察访核验
                dataMap.put("publicTest", "-");// 公众评议

                break;
            case "县直单位":

                break;


        }


        System.out.println("-------接口： /login/home");

        return ResultUtils.getSuccessResults(dataMap);

    }


    // 县处级领导
    @PostMapping("/leads")
    public Result<HashMap<String, Object>> otherData(@RequestBody UserAppDTO param) {

        HashMap dataMap = new HashMap();
        String department = param.getDepartment();
        if (StringUtils.isBlank(department)) {
            return ResultUtils.getResults(Result.Status.ERROR, "单位名称空了，啊钢你少传参数了", null);

        }
        switch (department){
            case "县委":
                department="县委办";
                break;
            case "县人大":
                department="人大办";
                break;
            case "县政府":
                department="政府办";

                break;
            case "县政协":
                department="政协办";
                break;
        }


       /* LeadersEntity entity = new LeadersEntity();
        entity.setDepartment(department);
        List<LeadersEntity> leadersEntities = leaderService.queryAll(entity);*/

        UserFilter userquery = new UserFilter();
        userquery.setIsLeader(1);
        userquery.setDepartment(department);
        List<UserFilter> userlists = userService.queryUsers(userquery);


        String currentYear = getCurrentYear();
        int i = 0;

        for (UserFilter item : userlists) {

            HashMap<String, Object> scores = getScores(item, currentYear);
            Double index = (Double) scores.get("index");
             Double xiangmu = ((Double) scores.get("xiangmu"));
            Double work = (Double) scores.get("work");
            double fianlscore =
                    index.doubleValue()+xiangmu.doubleValue() + work.doubleValue();


            item.setFianlScore(DataUtil.formatNumberDouble(2, fianlscore));

        }


        //计算排名 并列
        List<Map.Entry<Double, List<UserFilter>>> newDatas = userlists.stream().collect(Collectors.groupingBy(UserFilter::getFianlScore)).entrySet().stream()
                .sorted((o1, o2) -> -Double.compare(o1.getKey(), o2.getKey())).collect(Collectors.toList());
        int rank = 1;
        // 新计算并列排名
        for (Map.Entry<Double, List<UserFilter>> newData : newDatas) {

            int finalRank = rank;
            newData.getValue().forEach(o -> o.setRank(finalRank));
            rank = rank + newData.getValue().size();


        }

        dataMap.put("data", userlists);
        System.out.println("-------接口： /leads");
        return ResultUtils.getResults(Result.Status.SUCCESS, "阿纲，你看看数据对不对", dataMap);


    }

    /**
     * 各个考核得分
     * @param leader
     * @param year
     * @return
     */
    private HashMap<String, Object> getScores(UserFilter leader, String year) {
        HashMap<String, Object> data = new HashMap<>();
        //----- 指标----
        /*CountryIndicatorsFilter indexFilter = new CountryIndicatorsFilter();
        indexFilter.setIndexType("二级指标");
        //indexFilter.setLeadUnit(dto.getDepartcode());
        // 设置日期， 这个日期有点奇葩啊；干

        indexFilter.setMonthTime(DateUtils.getLastMonth());
        indexFilter.setDateTime(year);
        UserEntity userEntity = new UserEntity();
        userEntity.setUserPermissions("admin");
        //BeanUtils.copyProperties(userInfo, userEntity);
        List<CountryIndicatorsFilter> listIndesScore = cityIndexService.querySecondIndex(indexFilter, userEntity);*/

        /*
         *指标
         */
        EcoIndexentity ecoIndexentity = new EcoIndexentity();
        ecoIndexentity.setNickName(leader.getNickName().trim());
        List<EcoIndexentity> listIndesScore = duchaService.queryEcoIndex(ecoIndexentity);
        double sunindex = 0;
        for (EcoIndexentity item : listIndesScore) {
            if (StringUtils.isBlank(item.getNickName())) {
                continue;
            }
            /*
                指标得分标准 从自定义拿；
             */

            if (item.getNickName().contains(leader.getNickName())) {
                int rank = item.getRank();

                sunindex= sumEcoScore(rank);
            }
        }

        data.put("index", sunindex);
        //------ 项目----
        HashMap<String,Object> zdmap = new HashMap<>();

        String xiangmuparam ="{\"userPhone\":\"" +leader.getUserPhone().trim()+"\"}";
        String xiangmu = JSONObject.toJSON(xiangmuparam).toString();
        String zdscore="0";
        try {
            JSONObject jsonObject = HttpClientService.sendPost("http://120.78.158.120:8099"+SystemApiUtl.ZD_GET_LEADRANK, xiangmu, "http");
            if (ObjectUtils.isNotBlank(jsonObject)) {
                JSONArray data1 = jsonObject.getJSONArray("data");
                if (ObjectUtils.isNotBlank(data1)){
                    System.out.println(data1);
                    JSONObject dataobj = (JSONObject) data1.get(0);
                    if (ObjectUtils.isNotBlank(dataobj)){
                        zdscore = dataobj.getString("score");
                    }
                }
            }


        } catch (IOException e) {
            System.out.println("http://120.78.158.120:8099" + SystemApiUtl.ZD_GET_LEADRANK);
            e.printStackTrace();
        }
        data.put("xiangmu",sumZdXt(Double.parseDouble(zdscore)));

        //-------督查-----
        PishiEntity pishi = new PishiEntity();
        pishi.setNickName(leader.getNickName());
        List<PishiEntity> querypishi = duchaService.querypishi(pishi);
        ZhongDianWorkEntity work = new ZhongDianWorkEntity();
        work.setNickName(leader.getNickName());
        List<ZhongDianWorkEntity> querywork = duchaService.querywork(work);



        int pishisum = querypishi.stream().mapToInt(PishiEntity::getDealNum).sum();

        double works = querywork.stream().mapToDouble(ZhongDianWorkEntity::getFianlScore).sum();

        String nameValuePairs ="{\"mobile\":\"" +leader.getUserPhone().trim()+"\"}";
        String param2 = JSONObject.toJSON(nameValuePairs).toString();
        try {

            JSONObject jsonObject = HttpClientService.sendPost(SystemApiUtl.SERVICEADDRESS + ":" + SystemApiUtl.DUCAH_TEST+SystemApiUtl.DC_GET_LEADSCORE, param2, "http");
            if(ObjectUtils.isNotBlank(jsonObject))
            {
                JSONArray duchalead = jsonObject.getJSONArray("data");
                if (ObjectUtils.isNotBlank(duchalead)){
                    System.out.println(duchalead);
                    JSONObject dataobj = (JSONObject) duchalead.get(0);
                    if (ObjectUtils.isNotBlank(dataobj)){
                        double duchaword = DataUtil.doubleParse(  dataobj.getString("zdScore") );
                        works =works+duchaword;

                        int duchaPishij = DataUtil.integerParse(  dataobj.getString("pishijian") );
                        pishisum =pishisum+duchaPishij;

                        JSONObject leadobj = dataobj.getJSONObject("leader");
                        if(ObjectUtils.isNotBlank(leadobj))
                        {
                            String userId = leadobj.getString("userId");
                            data.put(leader.getUserPhone(),userId);
                            data.put("role",leadobj.getString("role"));
                        }
                    }
                }
            }





        } catch (IOException e) {
            e.printStackTrace();
        }


        //double works= sum+pishisum;
        data.put("work", works);
        data.put("pishi", sumPishiJian(pishisum));


        return data;

    }

    /**
     * 指标排名得分
     * @param rank
     * @return
     */
    double sumEcoScore(int rank){
        double sunindex = 0;
      /*  CriteriaFilter criteriaFilter = new CriteriaFilter();
        criteriaFilter.setCriteriaCode("JJZB");
        List<CriteriaEntity> Indexstandrad = criteriaService.selectListCriteria(criteriaFilter);
        CriteriaEntity criteria = Indexstandrad.get(0);
        if (rank > 0 && rank <= criteria.getGoodStandard()) {
            sunindex = sunindex + criteria.getGoodValue();
        }
        if (rank > (criteria.getGoodStandard()) && rank <=criteria.getGeneralStandard()) {
            sunindex = sunindex + criteria.getGeneralValue();
        }
        if (rank > (criteria.getGeneralStandard()) && rank < (criteria.getBadStandard()+1)) {
            sunindex = sunindex + criteria.getBadValue();
        }*/

        return  sunindex;
    }

    /**
     * 批示件
     * @param pishiNum
     * @return
     */
    double sumPishiJian(int pishiNum){
       double  sum=0;
       /* CriteriaFilter criteriaFilter = new CriteriaFilter();
        criteriaFilter.setCriteriaCode("PSJ");
        List<CriteriaEntity> psj = criteriaService.selectListCriteria(criteriaFilter);
        CriteriaEntity entity = psj.get(0);
        sum = pishiNum*entity.getCriteriaValue();*/

         sum=DataUtil.formatNumberDouble(2,sum);
        return sum;
    }

    /**
     * 攻坚协调；
     * @param gongjianNum
     * @return
     */
    double sumZdXt(double gongjianNum){
        CriteriaFilter criteriaFilter = new CriteriaFilter();
     /*   criteriaFilter.setCriteriaCode("XMJDXT");
        List<CriteriaEntity> psj = criteriaService.selectListCriteria(criteriaFilter);
        CriteriaEntity entity = psj.get(0);*/
        double sum =0;
      //  sum = gongjianNum*entity.getCriteriaValue();
        return  DataUtil.formatNumberDouble(2,sum);
    }

    //县处级领导二级页面
    @PostMapping("/leadsSecond")
    public Result<HashMap<String, Object>> leadsSecong(@RequestBody LeadersFilter param) {
        HashMap dataMap = new HashMap();
        List<LeadScoreDTO> dtos = new ArrayList<>();
        LeadersEntity entity = new LeadersEntity();
        List<UserFilter> leadersEntities=null;
        if (("slv").equals(param.getRole())) { //slv :SecondLeaderView 二级领导考评，县处级领导考评
            String userPhone = param.getUserPhone();
          /*  entity.setTelphone(userPhone);
            leadersEntities = leaderService.queryAll(entity);*/
            UserFilter userFilter = new UserFilter();
            userFilter.setUserPhone(userPhone);
            leadersEntities = userService.queryUsers(userFilter);


            //新的查询
           // LeadersEntity leadfilters = new LeadersEntity();
            UserFilter lead = leadersEntities.get(0);

            //List<LeadersEntity> allleads = leaderService.queryAll(leadfilters);
            UserFilter userFilter1 = new UserFilter();
            userFilter1.setDepartment(lead.getDepartment());
            userFilter1.setIsLeader(1);
            List<UserFilter> allleads = userService.queryUsers(userFilter1);
            String currentYear = getCurrentYear();
            int i = 0;

            for (UserFilter item : allleads) {

                HashMap<String, Object> scores = getScores(item, currentYear);
                Double index =  (Double) scores.get("index");
                // Double xiangmu = scores.get("xiangmu");
                Double work =  (Double)scores.get("work");
                double fianlscore =
                        index.doubleValue()/*+xiangmu.doubleValue()*/ + work.doubleValue();


                item.setFianlScore(DataUtil.formatNumberDouble(2, fianlscore));

            }


            //计算排名 并列
            List<Map.Entry<Double, List<UserFilter>>> newDatas = allleads.stream().collect(Collectors.groupingBy(UserFilter::getFianlScore)).entrySet().stream()
                    .sorted((o1, o2) -> -Double.compare(o1.getKey(), o2.getKey())).collect(Collectors.toList());
            int rank = 1;
            // 新计算并列排名
            for (Map.Entry<Double, List<UserFilter>> newData : newDatas) {

                int finalRank = rank;
                newData.getValue().forEach(o -> o.setRank(finalRank));
                rank = rank + newData.getValue().size();


            }


            int maxRank = allleads.stream().mapToInt(UserFilter::getRank).max().getAsInt();
            List<UserFilter> owners = allleads.stream().filter(entity1 -> entity1.getUserPhone().equals(userPhone)).collect(Collectors.toList());
            int ownRank = owners.get(0).getRank();
            dataMap.put("ownerRank",ownRank+"/"+maxRank);



        }else {
            long leadid = param.getLeadId().longValue();
            if (ObjectUtils.isBlank(leadid)) {
                return ResultUtils.getResults(Result.Status.ERROR, "leadId为空", null);

            }

            entity.setId(leadid);
            //leadersEntities = leaderService.queryAll(entity);
            UserFilter userFilter = new UserFilter();
            userFilter.setId(leadid);
            leadersEntities= userService.queryUsers(userFilter);
        }



        UserFilter leader = leadersEntities.get(0);
        String currentYear = getCurrentYear();

        HashMap<String, Object> scoresmap = getScores(leader, currentYear);



        dtos.add(new LeadScoreDTO( (Double)scoresmap.get("index"), "指标", null));

        //------项目得分=========


        //dtos.add(new LeadScoreDTO(scoresmap.get("xiangmu"),"项目",null));

        //--------重点工作====

        dtos.add(new LeadScoreDTO( (Double)scoresmap.get("work"), "重点工作", null));
        //-----批示---
        dtos.add(new LeadScoreDTO( (Double)scoresmap.get("pishi"), "批示件", null));

        List<EvaluateIndexFilter> newScorelist = evalScoreMagService.queryEvaMag(new EvaluateIndexFilter());

        for (EvaluateIndexFilter item : newScorelist) {

            String indexName = item.getIndexName();

            List<EvaluateScoreEntity> evaluateScoreEntities = evalScoreMagService.queryEvainfo(item.getId(), leader.getNickName().trim());
            double sum = evaluateScoreEntities.stream().mapToDouble(value -> value.getFianlScore()).sum();

            if("项目".equals(indexName))
            {
                HashMap<String, Object> scores = getScores(leader, currentYear);
                Double xmScore = (Double) scores.get("xiangmu");
                sum=sum+xmScore.doubleValue();

            }

            dtos.add(new LeadScoreDTO(sum, indexName, item.getId()));
        }

        dataMap.put("data", dtos);

        double ownerscore = dtos.stream().mapToDouble(LeadScoreDTO::getFianlScore).sum();
        dataMap.put("ownerScore",ownerscore);


        System.out.println("-------接口： /leadsSecond");
        return ResultUtils.getResults(Result.Status.SUCCESS, "县处级领导二级页面", dataMap);
    }

    //县处级领导三级页面
    @PostMapping("/leadsThree")
    public Result<HashMap<String, Object>> leadsThree(@RequestBody LeadersFilter param) {
        HashMap dataMap = new HashMap();
        List<ScoreDTO> dtos = new ArrayList<>();
        String currentYear = getCurrentYear();
        String assessment = param.getAssessment();
        UserFilter leader =null;

        Long leadid = param.getLeadId();

            if ( StringUtils.isBlank(param.getAssessment())) {
                return ResultUtils.getResults(Result.Status.ERROR, "leadId为空或者 考核事项 assessment为空", null);

            }
           //LeadersEntity entity = new LeadersEntity();
             UserFilter userFilter = new UserFilter();
            userFilter.setId(leadid);
            if(ObjectUtils.isBlank(leadid))
            {
                String userPhone = param.getUserPhone();
                userFilter.setUserPhone(userPhone);
            }



            //List<LeadersEntity> leadersEntities = leaderService.queryAll(entity);


        List<UserFilter> leadersEntities =userService.queryUsers(userFilter);
          leader = leadersEntities.get(0);
        int psjSumFromDucha =0;

        //批示件和重点工作的时候需要调用
        if("批示件".equals(assessment))
        {
            String nameValuePairs ="{\"mobile\":\"" +leader.getUserPhone().trim()+"\"}";
            String param2 = JSONObject.toJSON(nameValuePairs).toString();
            try {

                JSONObject jsonObject = HttpClientService.sendPost(SystemApiUtl.SERVICEADDRESS + ":" + SystemApiUtl.DUCAH_TEST+SystemApiUtl.DC_GET_LEADSCORE, param2, "http");


                System.out.println(jsonObject);
                if (ObjectUtils.isNotBlank(jsonObject)) {

                }

                JSONArray duchalead = jsonObject.getJSONArray("data");
                if (ObjectUtils.isNotBlank(duchalead)){
                    System.out.println(duchalead);
                    JSONObject dataobj = (JSONObject) duchalead.get(0);
                    if (ObjectUtils.isNotBlank(dataobj)){

                        int duchaPishij = DataUtil.integerParse(  dataobj.getString("pishijian") );
                        psjSumFromDucha =psjSumFromDucha+duchaPishij;



                    }
                }


            } catch (IOException e) {
                e.printStackTrace();
            }

        }



        switch (assessment) {
            case "指标":
               /* CountryIndicatorsFilter indexFilter = new CountryIndicatorsFilter();
                indexFilter.setIndexType("二级指标");
                //indexFilter.setLeadUnit(dto.getDepartcode());
                // 设置日期， 这个日期有点奇葩啊；干

                indexFilter.setMonthTime(DateUtils.getLastMonth());
                indexFilter.setDateTime(currentYear);

                //String tel = param.getUserPhone();
                // UserFilter userInfo = getUserInfo(tel);
                UserEntity userEntity = new UserEntity();
                userEntity.setUserPermissions("admin");
                //BeanUtils.copyProperties(userInfo, userEntity);
                List<CountryIndicatorsFilter> listIndesScore = cityIndexService.querySecondIndex(indexFilter, userEntity);
*/
                EcoIndexentity ecoIndexentity = new EcoIndexentity();
                // ecoIndexentity.setNickName(leader.getNickName().trim());
                List<EcoIndexentity> listIndesScore = duchaService.queryEcoIndex(ecoIndexentity);

                for (EcoIndexentity item : listIndesScore) {

                    if (StringUtils.isNotBlank(item.getNickName()) && item.getNickName().contains(leader.getNickName().trim())) {
                        ScoreDTO score = new ScoreDTO();
                        score.setIndexName(item.getIndexName());
                        score.setRank(item.getRank());
                        score.setEcoIndexId(item.getIndexId());
                        double fscore = 0;

                        int rank = item.getRank();
                        /*if (rank > 0 && rank <= 3) {
                            fscore = 10;
                        }
                        if (rank > 3 && rank < 9) {
                            fscore = 5;
                        }
                        if (rank > 8 && rank < 12) {
                            fscore = 3;
                        }*/
                        fscore =sumEcoScore(rank);
                        score.setFinalScore(fscore);
                        dtos.add(score);
                    }

                }
                break;
            case "项目":

              /*  HashMap<String,Object> nameValuePairs = new HashMap<>();
                nameValuePairs.put("checkObject",leader.getNickName().trim());
                nameValuePairs.put("checkType","攻坚任务");
                String param2 = JSONObject.toJSON(nameValuePairs).toString();*/
                String zdaparam ="{\"userPhone\":\"" +leader.getUserPhone()+"\"}";

                try {
                    JSONObject jsonObject = HttpClientService.sendPost("http://120.78.158.120:8099/zhApp/leader/queryProjectScoreInRes", zdaparam, "http");
                    JSONArray data=jsonObject.getJSONArray("data");
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject scoreInfo = (JSONObject) data.get(i);
                        ScoreDTO score = new ScoreDTO();
                        score.setRank(0);
                        String source = scoreInfo.getString("finalScore");
                        String gongjian = scoreInfo.getString("tackTaskScore");
                        double sourcedouble = DataUtil.doubleParse(source);
                        double gongjinScore = DataUtil.doubleParse(gongjian);
                        score.setFinalScore(sourcedouble);
                        score.setGongjianScore(gongjinScore);
                        score.setIndexName(scoreInfo.getString("projectName"));

                        ZDProcjectDTO zdProcjectDTO = JSONObject.toJavaObject(scoreInfo, ZDProcjectDTO.class);
                        score.setZdProject(zdProcjectDTO);

                        dtos.add(score);


                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }


                break;
            case "重点工作":


                ZhongDianWorkEntity work = new ZhongDianWorkEntity();
                work.setNickName(leader.getNickName());
                List<ZhongDianWorkEntity> querywork = duchaService.querywork(work);


                for (ZhongDianWorkEntity item : querywork) {
                    ScoreDTO score = new ScoreDTO();
                    score.setRank(0);
                    score.setFinalScore(item.getFianlScore());
                    score.setIndexName(item.getAssessment());
                    dtos.add(score);
                }

                HashMap<String, Object> scores = getScores(leader, currentYear);
                Object userId = scores.get(leader.getUserPhone());
                Object roleId = scores.get("role");
                String nameValuePairs ="{\"userId\":\"" +userId+""+"\",\"demo\":\"1\"}";
                String param2 = JSONObject.toJSON(nameValuePairs).toString();
                try {

                    JSONObject jsonObject = HttpClientService.sendPost(SystemApiUtl.SERVICEADDRESS + ":" + SystemApiUtl.DUCAH_TEST+SystemApiUtl.DC_GET_ZDWORK, param2, "http");
                    if (ObjectUtils.isNotBlank(jsonObject)) {
                        JSONObject duchalead = jsonObject.getJSONObject("data");
                        if (ObjectUtils.isNotBlank(duchalead)){

                            JSONArray workarray = duchalead.getJSONArray("list");


                            for (int i = 0; i < workarray.size(); i++) {
                                JSONObject leadobj = workarray.getJSONObject(i);
                                ScoreDTO score = new ScoreDTO();
                                score.setRank(0);
                                score.setFinalScore(10);
                                score.setIndexName(leadobj.getString("mainName"));
                                DCTaskDTO duchatask = new DCTaskDTO();

                                duchatask =JSONObject.toJavaObject(leadobj,DCTaskDTO.class);
                                duchatask.setUserId(userId+"");
                                duchatask.setRoleId(roleId+"");
                                score.setDcTask(duchatask);
                                dtos.add(score);

                            }
                        }
                    }




                } catch (IOException e) {
                    e.printStackTrace();
                }


                break;
            case "批示件":
                PishiEntity pishi = new PishiEntity();
                pishi.setNickName(leader.getNickName());
                List<PishiEntity> querypishi = duchaService.querypishi(pishi);
                for (PishiEntity item : querypishi) {
                    ScoreDTO score = new ScoreDTO();
                    score.setRank(0);
                    score.setFinalScore(sumPishiJian(item.getDealNum()+psjSumFromDucha));
                    score.setIndexName("批示件办理");
                    dtos.add(score);
                }


                break;
            default:
                //其他公用的新增的 得分类型
                if (ObjectUtils.isBlank(param.getEvaId())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "参数错误evaId不能为空", null);
                }

                List<EvaluateScoreEntity> scorlists = evalScoreMagService.queryEvainfo(param.getEvaId(), leader.getNickName().trim());
                for (EvaluateScoreEntity item : scorlists) {
                    if (!item.getLeadName().equals(leader.getNickName())) {
                        continue;
                    }
                    ScoreDTO score = new ScoreDTO();
                    score.setRank(item.getRank());
                    score.setFinalScore(item.getFianlScore());
                    score.setIndexName(item.getAssessment());
                    dtos.add(score);

                }


                break;


        }


        dataMap.put("data", dtos);


        System.out.println("-------接口： /leadsThree");
        return ResultUtils.getResults(Result.Status.SUCCESS, "县处级领导三级页面", dataMap);
    }


    // 其他角色考评(乡镇 县直单位 一级页面)
    @PostMapping("/depart/oneview")
    public Result<HashMap<String, Object>> deaprtdata(@RequestBody UserAppDTO param) {
            HashMap dataMap = new HashMap();

        String currentYear = getCurrentYear();

        String departType = param.getDepartType();

        List<DepartClassHead> heads = null;
        HashMap<String, Object> departScore = new HashMap<>();
        List<ScoreDTO> scoreDTOS = new ArrayList<>();
        heads = headService.queryByDatetime(currentYear);
        switch (departType) {
            case "乡镇":
                //   List<DepartmentEntity> towns = departmentService.selectForDepartment(null, "乡镇");
                departScore = yearSummaryScoreService.getDepartScore(heads, DateUtils.getLastMonth(currentYear), null, "乡镇", null);
                scoreDTOS = (List<ScoreDTO>) departScore.get("scoreData");
                break;

            case "县直单位":
                Long classId = param.getClassId();
                if (ObjectUtils.isBlank(classId)) {
                    return ResultUtils.getResults(Result.Status.ERROR, "classId，啊钢你少传参数了", null);

                }
                departScore = yearSummaryScoreService.getDepartScore(heads, DateUtils.getLastMonth(currentYear), null, "县直单位", classId + "");

                break;


        }
        scoreDTOS = (List<ScoreDTO>) departScore.get("scoreData");

        //计算排名 并列
        List<Map.Entry<Double, List<ScoreDTO>>> newDatas = scoreDTOS.stream().collect(Collectors.groupingBy(ScoreDTO::getFinalScore)).entrySet().stream()
                .sorted((o1, o2) -> -Double.compare(o1.getKey(), o2.getKey())).collect(Collectors.toList());
        int rank = 1;
        // 新计算并列排名
        for (Map.Entry<Double, List<ScoreDTO>> newData : newDatas) {

            int finalRank = rank;
            newData.getValue().forEach(o -> o.setRank(finalRank));
            rank = rank + newData.getValue().size();

        }

        dataMap.put("data", scoreDTOS);
        System.out.println("-------接口： /depart/oneview");
        return ResultUtils.getSuccessResults(dataMap);
    }

    // 县直单位获取classid
    @PostMapping("/getclassId")
    public Result<HashMap<String, Object>> getclassId(@RequestBody UserAppDTO param) {
        HashMap dataMap = new HashMap();
        List<DepartClassFilter> query = deptclass.query(new DepartClassFilter());


        String type = param.getType();
        if(!"all".equals(type))
        {
            Iterator<DepartClassFilter> iterator = query.iterator();
            while (iterator.hasNext()) {
                DepartClassFilter filter = iterator.next();
                if (filter.getClassname().contains("乡镇") || filter.getClassname().contains("领导")) {
                    iterator.remove();
                }
            }


        }

      /*  for (DepartClassFilter filter : query) {

            if (filter.getClassname().contains("乡镇")||filter.getClassname().contains("领导")) {
                query.remove(filter);
            }

        }*/
        dataMap.put("data", query);
        System.out.println("-------接口： /getclassId");
        return ResultUtils.getSuccessResults(dataMap);
    }


    // 其他角色考评(乡镇 县直单位 二级页面)
    @PostMapping("/depart/Secview")
    public Result<HashMap<String, Object>> deaprtdataSecond(@RequestBody UserAppDTO param) {


        DepartmentEntity departmentEntity = departmentService.selectByCode(param.getDepartCode());

        //工作督察
        String workScore = yearSummaryScoreService.getWorkScore(param.getDatetime(), param.getDepartCode());
        double sumWroks = DataUtil.doubleParse(workScore);
        // 指标得分
        double indexScore = yearSummaryScoreService.getIndexScore(param.getDatetime(), departmentEntity);

        // 正向激励
        String incetiveScore = yearSummaryScoreService.getIncetiveScore(param.getDatetime(), param.getDepartCode());

        // 查房合演

        //pingyi
        ArrayList<Map<String, String>> objects = new ArrayList<>();
        HashMap dataMap = new HashMap();

        dataMap.put("name", "指标得分"); //指标得分率
        dataMap.put("value", indexScore); //指标得分率
        objects.add(dataMap);
        dataMap = new HashMap();
        dataMap.put("name", "专项工作督查");
        dataMap.put("value", -sumWroks);
        objects.add(dataMap);
        dataMap = new HashMap();
        dataMap.put("name", "正向激励");
        dataMap.put("value", incetiveScore);
        objects.add(dataMap);
        dataMap = new HashMap();
        dataMap.put("name", "察访核验");
        dataMap.put("value", "-");
        objects.add(dataMap);
        dataMap = new HashMap();
        dataMap.put("name", "公众评议");
        dataMap.put("value", "-");
        objects.add(dataMap);
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", objects);
        System.out.println("-------接口： /depart/Secview");
        return ResultUtils.getSuccessResults(map);


    }


    /**
     * 单位选择下拉框
     * @param dto
     * @return
     */
    @PostMapping("/getdepts")
    public Result<HashMap<String,Object>> getDepts(@RequestBody UserAppDTO dto)
    {

        DepartmentFilter departmentFilter = new DepartmentFilter();
        List<DepartmentFilter> query = departmentService.query(departmentFilter);
        HashMap<String,Object> dataMap = new HashMap<>();
        dataMap.put("data",query);
        return  ResultUtils.getSuccessResults(dataMap);

    }



}
